package com.mashibing.smsgateway.config;

import com.mashibing.common.constant.RabbitMQConstants;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 针对性的配置，可以采用当前方式
 * @author SNA
 * @date 2025/9/22
 * @Description
 **/
@Configuration
public class RabbitMQConfig {

    private final int TTL = 10000;
    private final String FANOUT_ROUTING_KEY = "";


    // 声明死信队列，需要准备普通交换机，普通队列，死信交换机，死信队列
    @Bean
    public Exchange normalExchange() {
        return ExchangeBuilder.fanoutExchange(RabbitMQConstants.SMS_GATEWAY_NORMAL_EXCHANGE).build();
    }

    @Bean
    public Queue normalQueue() {
        Queue queue = QueueBuilder.durable(RabbitMQConstants.SMS_GATEWAY_NORMAL_QUEUE)
                .withArgument("x-message-ttl", TTL)
                .withArgument("x-dead-letter-exchange", RabbitMQConstants.SMS_GATEWAY_DEAD_EXCHANGE)
                .withArgument("x-dead-letter-routing-key", FANOUT_ROUTING_KEY)
                .build();
        return queue;
    }

    @Bean
    public Binding normalBinding(Exchange normalExchange, Queue normalQueue) {
        return BindingBuilder.bind(normalQueue).to(normalExchange).with("").noargs();
    }

    @Bean
    public Exchange deadExchange() {
        return ExchangeBuilder.fanoutExchange(RabbitMQConstants.SMS_GATEWAY_DEAD_EXCHANGE).build();
    }

    @Bean
    public Queue deadQueue() {
        return QueueBuilder.durable(RabbitMQConstants.SMS_GATEWAY_DEAD_QUEUE).build();
    }

    @Bean
    public Binding deadBinding(Exchange deadExchange, Queue deadQueue) {
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("").noargs();
    }






    /**
     * 配置类的方式修改RabbitMQ消费的方式
     * 创建一个自定义的RabbitMQ监听器容器工厂
     * 该工厂配置了并发消费者数量、预取消息数量和手动确认模式
     *
     * @param connectionFactory RabbitMQ连接工厂
     * @param configurer Rabbit监听器容器工厂配置器
     * @return 配置好的SimpleRabbitListenerContainerFactory实例
     */
//    @Bean
    public SimpleRabbitListenerContainerFactory gatewayContainerFactory(ConnectionFactory connectionFactory,
                                                                        SimpleRabbitListenerContainerFactoryConfigurer configurer) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConcurrentConsumers(5);
        factory.setPrefetchCount(10);
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        configurer.configure(factory, connectionFactory);
        return factory;
    }
}
